package top.byfree.jbyan.find.handler.impl;

import top.byfree.jbyan.find.FindApplication;
import top.byfree.jbyan.find.command.Arg;
import top.byfree.jbyan.find.handler.ResultHandler;
import top.byfree.jbyan.find.result.Line;
import top.byfree.jbyan.find.result.ResultSet;

import java.io.FileWriter;
import java.io.IOException;
import java.io.PrintWriter;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.List;

/**
 * @author jbyan
 * @since 2023/8/4
 */
public class FileResultHandler implements ResultHandler {
    @Override
    public void processor(Path path, List<ResultSet> resultSetList) {
        if (resultSetList.size() < 1) {
            return;
        }
        String out = FindApplication.ARGS.getStringArg(Arg.OUT);
        Path path1 = Paths.get(out);
        // 使用检索的文件名称，拼接结果文件
        String fileName = "_find_result.txt";
        String string = path.getFileName().toString();
        String targetPath = path1.toAbsolutePath() + "/" + string + "_" + Thread.currentThread().getId() + fileName;
        FileWriter fileWriter;
        try {
            fileWriter = new FileWriter(targetPath);
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
        PrintWriter printWriter = new PrintWriter(fileWriter);
        // 将结果写入文件
        for (int i = 0; i < resultSetList.size(); i++) {
            printWriter.println("结果" + (i + 1) + "\n");
            for (Line s : resultSetList.get(i).getLines()) {
                printWriter.println(s.getIndex() + ": " + s.getLine());
                printWriter.flush();
            }
            printWriter.println("\n");
        }

        printWriter.close();
    }
}
